<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Specification extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->config->load('config_maitai_shopapi');
	}
	
	public function index()
	{
		$sku = $this->uri->segment(2,0);
		
		// MALI KASI TO E HINDI DAPAT GANITO
		if($sku=='getthis')
		{
			$sku = $this->uri->segment(3, 0);
			$productName = urldecode($this->uri->segment(4,0));
			$this->getthis($sku, $productName);
		}
	
		// Get single item
		if($sku!='') {
			
			// curl call
			$ch = curl_init($this->config->item('maitai_shopapi_url') . $sku);    // initialize curl handle
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$product_array = curl_exec($ch);  
			$product = json_decode($product_array);
			
			$d['product_array'] = $product[0];
			
			$actualsku = $product[0]->sku;
			
			$d['maitai_like_url'] = $this->config->item('maitai_like_url') . $product[0]->id;	
			$d['maitai_get_this_url'] = base_url('index.php/specification/getthis/' . $actualsku . '/' . $product[0]->name);	
			//print_r($d); die();
			
			// Recommendations
			$session_id = $this->session->userdata('session_id');
			$source_page = base_url('index.php/specification/' . $actualsku);
			$reco_items = $this->getRecommendedItem($actualsku, null, $session_id, "", $source_page);
			$d['has_reco'] = false;
			
			if($reco_items) {
				$reco_items;
				$d['reco_transaction_id'] = array_pop($reco_items);
				// remove last items dapat 4 lang;
				$d['reco_items'] = $this->getBulkItems($reco_items);
				$d['has_reco'] = true;
				//die();
			}
		}
		
		
		
		$views['_content'] = "specification";
		$this->template->load('template_landing', $views, $d);
	}

	private function getBulkItems($skus = null)
	{
		if(count($skus)>0)
		{
			$bulkurl = $this->config->item('maitai_shopapi_reco_url') . implode("/", $skus);
	
			$ch = curl_init($bulkurl);    // initialize curl handle
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$product_array = curl_exec($ch);  
			$product = json_decode($product_array);
			
			return $product;
		} else {
			return false;
		}
	}
	
	
	/*
	 * 	Get the recommended items from Reco Engine using post method
	 * 	Total of 5 returned values
	 *  Return array NULL if empty
	 * 
	 *  Required:
	 *  - SKU
	 *  optional:
	 *  - userId or email address of logged-in user
	 *  - mobile number of logged-in user
	 */
	
    private function getRecommendedItem($sku = null, $emailId = null, $cookieId = null, $mobtel = null, $sourcePage = null)
    {
    	try {
	    	$api_url = "http://54.251.253.217:8080/RecommendationServices/api/getGaleRecommendedItem"; // PROD
	    	//$api_url = "http://54.254.101.48:8080/RecommendationServices/api/getGaleRecommendedItem"; // DEV
	    	
	    	$data = array(
	    				"username" => "galerecoengine",			// Forever value
						"password" => "g4l3r3c0en9in3",			// Forever value
	    				"email_id" => $emailId,
						"cookie_id" => $cookieId,
						"skuId" => $sku,						// required to have
						"mobile_number" => $mobtel,
						"item_type" => "gadget",				// Forever value
						"source_page" => $sourcePage                            // required to have
	    		);

	    	$json = json_encode($data);
	    		
			$ch = curl_init($api_url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
			
			$resp = curl_exec($ch);
			$result = json_decode($resp);
			curl_close($ch);  // Seems like good practice
		  	//$status = $result->status_code;
			//var_dump($result);
			//die();
	    	if($result==NULL)
				return NULL;
			
			if($result->status_code === "0")	// Successful
	    	{   
	    		$resulta = array();	    		
	    		
	    		if($this->isInPhonesDB($result->recommended_item_1))		array_push($resulta, $result->recommended_item_1); 
	    		if($this->isInPhonesDB($result->recommended_item_2))		array_push($resulta, $result->recommended_item_2); 
	    		if($this->isInPhonesDB($result->recommended_item_3))		array_push($resulta, $result->recommended_item_3); 
	    		if($this->isInPhonesDB($result->recommended_item_4))		array_push($resulta, $result->recommended_item_4); 
	    		if($this->isInPhonesDB($result->recommended_item_5))		array_push($resulta, $result->recommended_item_5); 
	    		//echo "Resulta:" ;var_dump($resulta);
	    		if(count($resulta)>0) {
	    			// Has return items
	    			array_push($resulta, $result->transaction_id);
	    			return $resulta;	
	    		} else {
	    			// Empty because sku is not in db
	    			return NULL;
	    		}
	    		
	    		//array_push($resulta, $this->isInPhonesDB($result->recommended_item_1), $this->isInPhonesDB($result->recommended_item_2), $this->isInPhonesDB($result->recommended_item_3), $this->isInPhonesDB($result->recommended_item_4), $this->isInPhonesDB($result->recommended_item_5), $result->transaction_id);
	    		//print_r($resulta); die();
	    	}
	    	
	    	return NULL; // empty
    	
    	} catch (Exception $e) {
    		die($e);
    	}
    }
	
    private function isInPhonesDB($sku)
    {
    	$this->config->load('config_maitai_tables');
    	$tbl_phones = $this->config->item('table_phones');

	    $this->db->cache_on();
	 	$query = $this->db->get_where($tbl_phones, array('gadgetSKU' => $sku));
	 	$this->db->cache_off();
    	
    	if($q = $query->result_array()) {
			return $sku;
		} else {
			return "";
		}
    }

    private function getthis($sku, $productName)
    {
    	// Get PRICE from DB
    	$price = "P" . $this->getPrice($sku);
    	
    	// Save to cookie sku + name;
    	$this->input->set_cookie(array('name'=>'sku', 'value'=>$sku, 'expire'=>0, 'path'=>'/'));
    	//$this->input->set_cookie(array('name'=>'gadget', 'value'=>$productName, 'expire'=>0, 'path'=>'/'));
    	//$this->input->set_cookie(array('name'=>'price', 'value'=>$price, 'expire'=>0, 'path'=>'/'));
    	
		if(isset($_COOKIE['mode'])){
		   if($_COOKIE['mode']=="edit")
    	      $url = base_url('index.php/summary');	
		   else
		      $url = base_url('index.php/promo');
		}
		else
		      $url = base_url('index.php/promo');
		
    	redirect($url, 'refresh');
    }
    
   	private function getPrice($sku)
   	{
   		$deviceInDBPrice = $this->device->getDevicePriceInDB($sku);
    	$price = ($deviceInDBPrice) ? $deviceInDBPrice : 0;
    	return $price;
   	}
}